package xiancheng;

public class TestThread implements Runnable{
    private static String winner;//胜利者
    @Override
    public void run() {
        for (int i = 1;i <= 101;i++){
            //模拟兔子睡觉
            if (Thread.currentThread().getName().equals("兔子") && i%10 ==0 ){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //判断比赛是否结束
            boolean flag = gameOver(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }
    }

    public boolean gameOver(int steps){
        //判断是否存在胜利者
        if (winner!=null){
            return true;
        }else if(steps>100){
            winner = Thread.currentThread().getName();
            System.out.println("winner is"+winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        new Thread(testThread,"乌龟").start();
        new Thread(testThread,"兔子").start();
    }
}

//多个线程同时操控一个对象
//买票的例子
/*public class TestThread implements Runnable{
    private int tickNums = 10;//票数
    @Override
    public void run() {
        while (true) {
            if (tickNums<=0){
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+tickNums--+"张票");
        }
    }
    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        new Thread(testThread,"小明").start();
        new Thread(testThread,"小龙").start();
        new Thread(testThread,"黄牛").start();
    }
}*/


/*
public class TestThread implements Runnable{
    @Override
    public void run() {
        //run方法线程体
    }
    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread testThread = new TestThread();
        //创建线程对象，通过线程对象来开起我们的线程，代理
        Thread thread = new Thread(testThread);
        thread.start();
        //new Thread(testThread).start();//简化写法
    }
}
*/

/*public class TestThread extends Thread{
    @Override
    public void run() {
        //run方法线程体
    }
    public static void main(String[] args) {
        //main线程，主线程
        TestThread testThread = new TestThread();
        testThread.start();
    }
}*/
